#include "MainView.h"
#include "ui_MainView.h"

#include <QStandardPaths>
#include <QMessageBox>
#include <QDir>
#include <QDesktopServices>

#include <QDropEvent>
#include <QMimeData>

#include <QDomDocument>
#include <QDomElement>
#include <QDomNode>
#include <QThread>
#include <QRegExp>
#include <QSvgRenderer>
#include <QPainter>

#include <QDebug>

MainView::MainView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainView)
{
    ui->setupUi(this);
    setAcceptDrops(true);

    ui->parentEdit->setText(QStandardPaths::writableLocation(QStandardPaths::HomeLocation));

    connect(ui->runBtn,&QPushButton::clicked,this,&MainView::onRun);
}

MainView::~MainView()
{
    delete ui;
}

void MainView::dragEnterEvent(QDragEnterEvent *e)
{
    const QString &path = e->mimeData()->urls().first().toLocalFile();
    ui->label->setText(path);
    m_srcFile = path;
}

void MainView::dragMoveEvent(QDragMoveEvent *e)
{
    qDebug() << e->mimeData()->urls();
}

void MainView::dropEvent(QDropEvent *event)
{
    qDebug() << event->mimeData()->urls();
}

void MainView::onRun()
{
    if (m_srcFile.isEmpty()){
        QMessageBox::warning(this,"error","please drop src file");
        return;
    }

    if (ui->folderEdit->text().isEmpty()) {
        QMessageBox::warning(this,"error","please set folder");
        return;
    }

    QString outPathPrefix;

    if (ui->parentEdit->text().endsWith("/"))
        outPathPrefix = ui->parentEdit->text();
    else
        outPathPrefix = ui->parentEdit->text() + "/";

    QDir dir(outPathPrefix);
    dir.mkdir(ui->folderEdit->text());
    outPathPrefix += ui->folderEdit->text() + "/";

    QFile file(m_srcFile);

    QFile svgTemplate(":/svg/svg_template.txt");
    if (!svgTemplate.open(QIODevice::ReadOnly)) {
        qDebug() << "error";
        return ;
    }
    QString templateBytes = svgTemplate.readAll();

    QDomDocument doc("tkgdocument");

    if (!file.open(QIODevice::ReadOnly))
        return ;

    QRegExp svgExp("<svg>.*</svg>");
    QString svgStr = file.readAll();
    file.close();

    svgExp.indexIn(svgStr);
    qDebug() << "init svg" << doc.setContent(svgExp.cap());

    QDomElement docElem = doc.documentElement();
    QDomNodeList symbolList = docElem.elementsByTagName("symbol");

    for (int i = 0; i < symbolList.size(); ++i) {
        const QDomNode &node = symbolList.item(i);
        if (node.isElement()) {
            QString fileName = node.toElement().attribute("id").replace("icon-","");
            if (node.isNull()) {
                return ;
            }

            qDebug() << "file name:" << fileName;
            QString result;
            QTextStream stream(&result);
            node.save(stream,0);

            //把symbol符号去掉
            QRegExp exp("<symbol.*>");
            exp.setMinimal(true);
            exp.indexIn(result);
            result.replace(exp.cap(),"");
            result.replace("</symbol>","");

            QString path = outPathPrefix + QString("%1.svg").arg(fileName);

            QFile newSvg(path);
            if (newSvg.open(QIODevice::WriteOnly)) {
                newSvg.write(templateBytes.arg(result).toUtf8());
                newSvg.close();

                QSvgRenderer render(path);
                render.isValid();

                QImage img(256,256,QImage::QImage::Format_ARGB32);
                img.fill(0);
                QPainter p(&img);
                p.setRenderHint(QPainter::Antialiasing);
                render.render(&p);

                QStringList list = ui->sizeEdit->text().split(";");
                for (QString size : list) {
                    if (size.toInt() <= 0)
                        continue;

                    /* NOTICE:这里可以支持多个以;分割的尺寸，但是文件名会被最后一个覆盖，如果您想生成多个，那么需要更改一下名称即可，比如加个size后缀 */
                    QString pngPath = outPathPrefix + QString("%1.png").arg(fileName);

                    img.scaled(size.toInt(),size.toInt(),Qt::KeepAspectRatio,Qt::SmoothTransformation).save(pngPath);
                    if (ui->box2x->isChecked()) {
                        QString png2xPath = outPathPrefix + QString("%1@2x.png").arg(fileName);
                        img.scaled(size.toInt()*2,size.toInt()*2,Qt::KeepAspectRatio,Qt::SmoothTransformation).save(png2xPath);
                    }

                    if (ui->box3x->isChecked()) {
                        QString png3xPath = outPathPrefix + QString("%1@3x.png").arg(fileName);
                        img.scaled(size.toInt()*3,size.toInt()*3,Qt::KeepAspectRatio,Qt::SmoothTransformation).save(png3xPath);
                    }

                    if (ui->box4x->isChecked()) {
                        QString png4xPath = outPathPrefix + QString("%1@4x.png").arg(fileName);
                        img.scaled(size.toInt()*4,size.toInt()*4,Qt::KeepAspectRatio,Qt::SmoothTransformation).save(png4xPath);
                    }
                }
            }
        }
#ifdef Q_OS_MAC
        QDesktopServices::openUrl(QUrl("file://" +outPathPrefix));
#else
        QDesktopServices::openUrl(QUrl("file:///" +outPathPrefix));
#endif
    }
}

void MainView::onClear()
{

}
